package com.masterrabbit.gyf.Controller;
import com.alibaba.fastjson2.JSONObject;
import com.masterrabbit.common.core.utils.uuid.UUID;
import com.masterrabbit.gyf.domain.Coupons;
import com.masterrabbit.gyf.domain.UserCoupons;
import com.masterrabbit.gyf.mapper.CouponsMapper;
import com.masterrabbit.gyf.mapper.UserCouponsMapper;
import com.masterrabbit.masterrabbitapigyf.api.RemoteTicketInitService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class TicketConsumerController {
    @Autowired
    private RemoteTicketInitService remoteTicketInitService;
    @Autowired
    private CouponsMapper couponsMapper;
    @Autowired
    private UserCouponsMapper userCouponsMapper;
    //开始监听消息队列(这个队列是死信队列)
    @RabbitListener(queues = "myq2")
    public void receive1(Message message) {
        String msg = new String(message.getBody());
        JSONObject obj = JSONObject.parse(msg);

        //解析数据
//        String couponsJson = obj.getString("coupons");
//        String createTime = obj.getString("now");
//        Coupons coupons = JSONObject.parseObject(couponsJson, Coupons.class);
//
//        System.out.println("监听参数:"+coupons);
        System.out.println("自动监听消息");
        remoteTicketInitService.initTickets(obj);

    }



    //监听优惠券抢票成功列表
    @RabbitListener(queues = "successmq1")
    public void receive2(Message message, Channel channel) throws IOException {
        try{
            System.out.println("抢票成功后进行监听事件处理");
            //抢票成功，开始插入数据库
            String s = new String(message.getBody());
            JSONObject obj = JSONObject.parse(s);
            Object o = obj.get("coupons");
            Object o1 = obj.get("userCoupons");
            Coupons coupons = JSONObject.parseObject(o.toString(), Coupons.class);
            UserCoupons userCoupons = JSONObject.parseObject(o1.toString(), UserCoupons.class);

            //开始往数据库中插入
            couponsMapper.insert(coupons);
            userCoupons.setCouponId(coupons.getCouponId());
            userCouponsMapper.insert(userCoupons);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }

    }

}
